#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

#include "proto.h"

int main(void)
{
	int tcp_socket, accepted_socket;
	struct sockaddr_in laddr;
	struct msg_st buf;
	pid_t pid;

	tcp_socket = socket(AF_INET, SOCK_STREAM, 0);
	if (-1 == tcp_socket) {
		perror("socket()");
		exit(1);
	}

	laddr.sin_family = AF_INET;
	inet_aton(SERVER_IP, &laddr.sin_addr);
	laddr.sin_port = htons(SERVER_PORT);
	if (-1 == bind(tcp_socket, (struct sockaddr *)&laddr, sizeof(laddr))) {
		perror("bind()");
		goto ERROR;
	}

	if (-1 == listen(tcp_socket, 80)) {
		perror("listen()");
		goto ERROR;
	}

	while (1) {
		// accepted_socket用于通行的
		accepted_socket = accept(tcp_socket, NULL, NULL);
		if (-1 == accepted_socket) {
			perror("accept()");
			goto ERROR;
		}
		pid = fork();
		if (-1 == pid) {
			perror("fork()");
			goto ERROR;
		} 
		if (0 == pid) {
			sleep(3);
			strncpy(buf.data, "hello", 6);
			write(accepted_socket, &buf, 6);
			close(accepted_socket);
			exit(0);
		}
	}

	close(tcp_socket);

	return 0;
ERROR:
	close(tcp_socket);
	exit(1);
}


